package com.cwx.mychat.websocket;

import com.cwx.mychat.config.AppConfig;
import com.cwx.mychat.utils.stringUtils.StringUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 作者： cwx
 * 时间： 2024/9/20 9:43
 * 版本： 1.0
 * 注释：
 */
@Slf4j
@Component
public class NettyWebSocketStart {

    private static EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private static EventLoopGroup workGroup = new NioEventLoopGroup();

    @Resource
    private HandlerWebSocket handlerWebSocket;

    @Resource
    private AppConfig appConfig;

    /**
     * 服务器销毁前关闭EventLoopGroup
     */
    @PreDestroy
    public void close(){
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

    /**
     * 异步启动netty，防止阻塞
     */
    @Async("threadPoolTaskExecutor")
    public void start(){
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup);
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //设置处理器
                            //对http协议的支持，使用http编码器，解码器
                            pipeline.addLast(new HttpServerCodec());
                            //聚合解码
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            pipeline.addLast(new HandlerHeartBeat());
                            //将http协议升级为ws协议，对websocket支持
                            pipeline.addLast(new WebSocketServerProtocolHandler(appConfig.getWsPath(), null, true, 64*1024, true, true, 10000L));
                            //添加处理器
                            pipeline.addLast(handlerWebSocket);
                        }
                    });
            //获取ws配置
            Integer wsPort = appConfig.getWsPort();
            String property = System.getProperty("ws.port");
            if (!StringUtil.isEmpty(property)) {
                wsPort = Integer.parseInt(property);
            }
            ChannelFuture channelFuture = serverBootstrap.bind(wsPort).sync();
            log.info("netty服务启动成功，端口号:{} (ws) with context path '{}'", appConfig.getWsPort(), appConfig.getWsPath());
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("启动失败");
            throw new RuntimeException(e);
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
